<template>
  <div class="feedback-page" :class="{ 'slide-in': isVisible }">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
      <span class="title">意见反馈</span>
    </div>

    <div class="content">
      <van-form @submit="handleSubmit" ref="formRef">
        <div class="form-section">
          <div class="form-item">
            <div class="label required">问题描述</div>
            <van-field v-model="formData.description" type="textarea" placeholder="请详细描述您遇到的问题或建议..." rows="6"
              maxlength="500" show-word-limit :rules="[{ required: true, message: '请输入问题描述' }]" />
          </div>

          <div class="form-item">
            <div class="label">问题截图（最多3张）</div>
            <div class="upload-container">
              <div class="upload-wrapper">
                <van-uploader v-model="formData.images" :max-count="3" :after-read="afterRead"
                  :before-delete="beforeDelete" multiple accept="image/*">
                  <div class="upload-box">
                    <van-icon name="plus" size="32" />
                  </div>
                </van-uploader>
                <span class="upload-text">点击选择图片上传</span>
              </div>
              <div class="upload-preview-list" v-if="formData.images.length > 0">
                <div class="preview-item" v-for="(image, index) in formData.images" :key="index">
                  <img :src="getImageUrl(image)" alt="预览图" class="preview-image" />
                  <van-icon name="cross" class="delete-icon" @click="handleDeleteImage(index)" />
                </div>
              </div>
            </div>
          </div>

          <div class="form-item">
            <div class="label">联系方式（QQ）</div>
            <van-field v-model="formData.contact" placeholder="请输入您的QQ号（选填）" type="tel" maxlength="20" />
          </div>
        </div>

        <div class="submit-section">
          <van-button round block type="primary" native-type="submit" :loading="submitting" class="submit-btn">
            提交反馈
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import type { FormInstance, UploaderFileListItem } from 'vant'

// Vant组件会自动导入，这里只需要导入类型

const router = useRouter()
const formRef = ref<FormInstance>()
const isVisible = ref(false)
const submitting = ref(false)

// 表单数据
const formData = ref({
  description: '',
  images: [] as UploaderFileListItem[],
  contact: ''
})

// 图片上传后处理
const afterRead = (file: UploaderFileListItem | UploaderFileListItem[]) => {
  // 这里可以添加图片压缩或上传到服务器的逻辑
  // 目前只是本地预览
  const files = Array.isArray(file) ? file : [file]
  console.log('图片上传:', files)
}

// 删除图片前处理
const beforeDelete = (file: UploaderFileListItem, detail: { index: number }) => {
  return true
}

// 处理删除图片
const handleDeleteImage = (index: number) => {
  formData.value.images.splice(index, 1)
}

// 获取图片URL
const getImageUrl = (image: UploaderFileListItem): string => {
  if (image.url) return image.url
  if (image.content) return image.content
  if (image.file) {
    // 如果是 File 对象，创建临时 URL
    return URL.createObjectURL(image.file)
  }
  return ''
}

// 清空表单
const resetForm = () => {
  formData.value = {
    description: '',
    images: [],
    contact: ''
  }
  // 重置表单验证状态
  formRef.value?.resetValidation()
}

// 处理返回
const handleBack = () => {
  // 触发退出动画
  isVisible.value = false
  // 等待动画完成后再路由返回
  setTimeout(() => {
    router.back()
    // 返回后清空表单
    resetForm()
  }, 300)
}

// 处理表单提交
const handleSubmit = async () => {
  // 验证表单
  if (!formData.value.description.trim()) {
    showToast('请输入问题描述')
    return
  }

  submitting.value = true

  try {
    // 模拟提交延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    // 这里可以添加实际的提交逻辑
    console.log('提交反馈:', {
      description: formData.value.description,
      images: formData.value.images,
      contact: formData.value.contact
    })

    // 先触发退出动画
    isVisible.value = false

    // 等待动画完成后返回
    setTimeout(() => {
      router.push('/my')

      // 返回后清空表单
      resetForm()

      // 返回后再显示成功提示
      setTimeout(() => {
        showToast({
          message: '反馈提交成功',
          position: 'top'
        })
      }, 100)
    }, 300)
  } catch (error) {
    showToast('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 触发进入动画
const triggerEnterAnimation = () => {
  // 确保初始状态是隐藏的（translateX(100%)）
  isVisible.value = false

  // 延迟一帧确保DOM已渲染，然后触发进入动画
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      isVisible.value = true
    })
  })
}

// 组件挂载时触发动画
onMounted(() => {
  triggerEnterAnimation()
})

// 组件激活时触发动画（处理 keep-alive 情况）
onActivated(() => {
  triggerEnterAnimation()
})

onUnmounted(() => {
  isVisible.value = false
  // 组件卸载时清空表单
  resetForm()
})
</script>

<style scoped lang="less">
.feedback-page {
  width: 100vw;
  height: 100vh;
  background-color: #f8f8f8;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;

  &.slide-in {
    transform: translateX(0);
  }

  .header {
    width: 100%;
    height: 6vh;
    padding: 0 4vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    gap: 3vw;
    border-bottom: 1px solid #f5f5f5;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 10;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .back-icon {
      font-size: 18px;
      color: #333;
      cursor: pointer;
      transition: opacity 0.2s;

      &:active {
        opacity: 0.7;
      }
    }

    .title {
      font-size: 17px;
      font-weight: 600;
      color: #333;
    }
  }

  .content {
    width: 100%;
    min-height: calc(100vh - 6vh);
    padding: 3vh 4vw;
    box-sizing: border-box;
    padding-bottom: 10vh;

    .form-section {
      background-color: #fff;
      border-radius: 8px;
      padding: 3vh 4vw;
      margin-bottom: 3vh;

      .form-item {
        margin-bottom: 4vh;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          margin-bottom: 2vh;

          &.required {
            &::before {
              content: '*';
              color: #ff4444;
              margin-right: 4px;
            }
          }
        }

        :deep(.van-field) {
          background-color: #f8f8f8;
          border-radius: 8px;
          padding: 2vh 3vw;

          .van-field__control {
            font-size: 14px;
            color: #333;
            line-height: 1.6;
          }

          .van-field__word-limit {
            color: #999;
            font-size: 12px;
          }
        }

        .upload-container {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          flex-wrap: wrap;

          .upload-wrapper {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;

            :deep(.van-uploader) {
              .van-uploader__upload {
                width: 100px;
                height: 100px;
                margin: 0;
                border: 1px dashed #d9d9d9;
                border-radius: 12px;
                background-color: #fafafa;
                position: relative;

                .upload-box {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  width: 100%;
                  height: 100%;
                  color: #999;
                }
              }

              .van-uploader__preview {
                display: none;
              }
            }

            .upload-text {
              font-size: 12px;
              text-align: center;
              color: #999;
              white-space: nowrap;
            }
          }

          .upload-preview-list {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            flex: 1;

            .preview-item {
              position: relative;
              width: 100px;
              height: 100px;
              border-radius: 12px;
              overflow: hidden;
              border: 1px solid #e8e8e8;

              .preview-image {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }

              .delete-icon {
                position: absolute;
                top: 4px;
                right: 4px;
                width: 20px;
                height: 20px;
                background-color: rgba(0, 0, 0, 0.6);
                color: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                cursor: pointer;
                transition: background-color 0.2s;

                &:active {
                  background-color: rgba(0, 0, 0, 0.8);
                }
              }
            }
          }
        }
      }
    }

    .submit-section {
      padding: 0 4vw;

      .submit-btn {
        height: 48px;
        font-size: 16px;
        font-weight: 500;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      }
    }
  }
}
</style>
